//
//  StatusListViewModel.swift
//  sina
//
//  Created by DXapple on 15/11/19.
//  Copyright © 2015年 sqlite. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
import SDWebImage

class StatusListViewModel: NSObject {
    func lodata(since_id since_id: Int,max_id: Int, finished: (array: [Status]?) ->() ) {
       
        
        
//        let AFN = AFHTTPSessionManager()
//        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
         let urlString = "2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel().token else {
            
            SVProgressHUD.showErrorWithStatus("没有登录")
            return
            
        }
        var parmenters = ["access_token" : token]
        if since_id > 0 {
            //添加since_id 对应键值
            parmenters["since_id"] = "\(since_id)"
        
        }
        if max_id > 0 {
        parmenters["max_id"] = "\(max_id - 1 )"
        }
        
        
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parmaters: parmenters) { (result, error) -> () in
            
            if error != nil {
            
            finished(array: nil)
                return
            }
            if let array = result!["statuses"] as? [[String : AnyObject]] {
            
            var list = [Status]()
                for item in array {
                    let s = Status(dict: item)
                    list.append(s)
                }
                //完成回调
//                finished(array: list)
                StatusListViewModel.cacheStatusImage(list, finished: finished)
                
            }
        }
    }
    private class func cacheStatusImage(array: [Status],finished: (array: [Status]?) ->()){
        
        if array.count == 0 {
            //完成回调
            finished(array: nil)

            return}
        
        //创建群组
        let group = dispatch_group_create()
        //遍历模型数组
        for s in array {
            if let imageurls = s.pictureURLs{
                if imageurls.count != 1{
                    
                    continue }
                for url in imageurls {
                //开始下载图片  异步加载图片的开始  想群组中添加异步任务
                    
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_ , _, _, _, _) -> Void in
//                            print("单张图片下载完成")
                        
                            //一部人物离开群组
                        dispatch_group_leave(group)
                    })
                }
            }
        }
        //监听任务
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //主线程完成回调
//            print("所有异步图片下载完成")
            finished(array: array)
            
        }
        
        
    }

    
    
}




